/**
 * Copyright(C) com.allinpay - 老纳也
 * 
 * @author 陆某人
 *
 * @since 2013年9月25日
 * @description: <描述>
 * 
 */

var mcArray = new Array();      // 商品分类
var menuCart = new Array();    // 点餐车信息
var request_complete = true;
var nMenuSecHeight = jQuery(window).height() - 44 - 50;
var lastSrlTop = 0;

$(document).ready(function() {

	mc_req();
	
	$("#content").height(nMenuSecHeight);
	$("#menu_list_sec").scroll(function(e) {
		var nScrollHight = $("#menu_list_sec")[0].scrollHeight;
		var nScrollTop = $("#menu_list_sec").scrollTop();
		
		if (nScrollTop > lastSrlTop) {
			lastSrlTop = nScrollTop;
	        if(nScrollTop + nMenuSecHeight >= nScrollHight - 30) {
	          scroll_loading();
	        };
		}
		e.preventDefault();
	});
	
});

// 请求商品分类
function mc_req() {
	ajax_post_json("apis/menu/category", {"rid" : r_id, "access_token":access_token }, m_beforeSend, mc_success, m_error, m_complete);
}

var ajax_data = {
	"rid" : r_id,
	"category_id" : 0,        // 注意赋值
	"startindex" : 0,
	"orderby" : "id",            // 默认按id排序
	"access_token":access_token
};

// 针对某分类请求menuitems
function mi_request() {
	ajax_post_json("apis/menu/items", ajax_data, m_beforeSend, mi_success, m_error, m_complete);
}

function scroll_loading() {
	if (request_complete) {
		var mcObj = getMenuCat(ajax_data.category_id);
		ajax_data.startindex = mcObj.cursor;
		$("#loading_prompt").css({display:"block"});
		mi_request();
		request_complete = false;
	}
}

function m_beforeSend(xhr){
	showLoadingDiv();
};
function m_error(XMLHttpRequest, textStatus, errorThrown){
	request_complete = true;
};
function m_complete(event,xhr,options){
	request_complete = true;
	hideLoadingDiv();
};

function mc_onClick(index, mc_id){
	if (ajax_data.category_id != mc_id){  // 排除重复点击同一个菜单类型
		ajax_data.category_id = mc_id;
		
		lastSrlTop = 0; // scrolltop clear
		
		//build_mc(index);
		$("div[name='category']").each(function(){
			$(this).addClass("cuisine");
			$(this).removeClass("click-cuisine");
			if (this.id == mc_id) {
				$(this).addClass("click-cuisine");
			}
		});
		
		var menucat = getMenuCat(mc_id);
		
		// js里面保存过给分类下的商品列表，就利用js中数据重建列表
		$("#menu_list_sec").empty();
		$("#menu_list_sec").scrollTop(0);
		
		if (menucat.menuHtml.length>0) {
			ajax_data.startindex=menucat.cursor;
			$("#menu_list_sec").append(menucat.menuHtml);
		}else{
			ajax_data.startindex=0;
			mi_request();
		}
	}
}

function newMenuCategory(id, name, highlight){
	var m = new Object();
	m.id=id;                         // menu category id
	m.name=name;               // menu category name
	m.highlight=highlight;       // menu highlight
	m.cursor=0;                   // menu item list cursor
	m.items= new Array();    // menu items for each category
	m.menuHtml="";
	return m;
}

function newMenuItem(id, name, pic, desc, price, count, comments){
	var m = new Object();
	m.id = id;
	m.name = name;
	m.pic = pic;
	m.desc=desc;
	m.price = price;
	m.count = count;
	m.comments = comments;
	return m;
}

function newCartItem(id, count){
	var c = new Object();
	c.id = id;
	c.count = count;
	return c;
}

function getMenuCat(cid){
	var obj = null;
	$.each(mcArray, function(index, item) {
		if (item.id == cid){
			obj = item;
			return false;
		}
	});
	if (isValide(obj)){
		return obj;
	}else{
		//alert("getMenuCat: end " + cid);
		return newMenuCategory(0,"");
	};
}

function mc_success(data) {
	if (data.type == "data") {
		var t_id = "";   // 临时记录第一个分类的id
		var n = 0;
		$.each(data.content, function(index, item) {
			if (index == 0) t_id = item.id;
			mcArray[n++] = newMenuCategory(item.id, item.name, item.highlight);
		});
		
		if (t_id != "") {
			ajax_data.category_id = t_id;
			ajax_data.startindex=0;
			mi_request();
		};
		
		if (n > 0) {
			build_mc(0);  // 组建左边的菜单分类层
		}
		
	} else if (data.type = "msg") {
		//$("#default_prompt").css({'display': ""});
	};
};

function build_mc(cur_selected_index){
	var div_item_list = $("#menu_cat_sec");
	div_item_list.empty();
	
	$.each(mcArray, function(index, item) {
		var divItem=$("<div style='position:relative;"+((index == 0)?"border-top:1px solid #ababab;":"")+"' name=\"category\" id=\""+item.id+"\" onclick=\"javascript:mc_onClick('"+index+"', '"+item.id+"')\">"+item.name+"</div>");
		if (index == cur_selected_index) divItem.addClass("click-cuisine");
		else divItem.addClass("cuisine");
		
		if (item.highlight) {
			divItem.addClass("red-c");
		}
		div_item_list.append(divItem);
	});
}

function mi_success(data){
	if (data.type == "data") {
		var mcObj = getMenuCat(data.content.category_id);
		var t_cursor = mcObj.cursor;
		
		$.each(data.content.items, function(index, item) {
			// 记录该分类下所有的商品信息
			mcObj.items[mcObj.cursor++] = newMenuItem(item.id, item.name, item.picPath, item.description, item.price, 0, item.comments);
		});
		
		if (data.content.category_id == ajax_data.category_id) {
			//build_mi(data.content.category_id, t_cursor);
			if (mcObj.cursor > t_cursor) {
				build_mi(ajax_data.category_id, t_cursor);
			}
		}else{
			build_mi(ajax_data.category_id, 0);
		}
		
		
	} else if (data.type = "msg") {
		ef_alert(data.content);
	}

	$("#loading_prompt").css({"display":"none"});

	request_complete = true;
}

function build_mi(cid, start){
	var mcObj = getMenuCat(cid);
	if (mcObj.items.length == 0) $("#defaulthit").css({display: ""});
	
    var menuHtml = "";
	$.each(mcObj.items ,function(index,item){
		if (index >= start){
			menuHtml += "<div class='list-block-c-food cf' "+((index == 0)?"style='border-top:1px solid #ababab;'":"")+" onclick=\"javascript:show_item_pic('"+item.name+"','"+item.price+"', $('#img"+index+"').attr('src'), '"+item.desc+"')\">";
			menuHtml += "<img id='img"+index+"' src='"+imgPath+"/" + item.pic + "' class='img-border' style=\"width:70px; height:70px; float:left;\" />";
			menuHtml += "<div class='bl-m-c cf' >";
			menuHtml += "<p class='bl-tit' >" + item.name + "</p>";
			menuHtml += "<p class='bl-price' >单价：" + item.price + "元</p>";
			menuHtml += "</div>";
			menuHtml += "</div>";
		}
	});
	mcObj.menuHtml += menuHtml;

	$("#menu_list_sec").append(menuHtml);
}


var isOk2Hide = false;
function show_item_pic(name, price, imgpath, desc) {
	$("#pop_image").attr('src',imgpath);
	$("#pop_name").empty();
	$("#pop_name").append(name + "<font style='font-size:12px; margin-left: 10px;' > ￥" + price + "<font>");
	$("#pop_desc").html(desc);

	if ($("#pop_show").is(":visible")) {
		return;
	}
	var top = (($(window).height() / 2) - ($("#pop_show").outerHeight() / 2))-25;
	var left = (($(window).width() / 2) - ($("#pop_show").outerWidth() / 2));
	if( top < 0 ) top = 0;
	if( left < 0 ) left = 0;

	$("#pop_show").css({
		top: top + 'px',
		left: left + 'px'
	});
	
	$(".main").click(function(){
		if (isOk2Hide == true && $("#pop_show").is(":visible")) {
			isOk2Hide = false;
			$("#pop_show").hide();
		}
	});
	
	$("#pop_show").fadeTo(200, 1, function() {
		isOk2Hide = !isOk2Hide;
	});
}

function hidenPopShow(){
	isOk2Hide = false;
	$("#pop_show").fadeOut(200);
}

